﻿using System.Globalization;
using System.Text;
using System.Windows.Data;

namespace Assets.Converters
{
    public class IconStringConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value is string stringValue && !string.IsNullOrEmpty(stringValue))
            {
                StringBuilder decodedString = new StringBuilder();

                // 使用 "&#x" 和 ";" 分割字符串，获取十六进制编码
                string[] strlist = stringValue.Split(
                    new string[] { "&#x", ";" },
                    StringSplitOptions.RemoveEmptyEntries
                );

                // 遍历分割后的字符串数组，将十六进制转换为字符
                for (int i = 0; i < strlist.Length; i++)
                {
                    if (
                        int.TryParse(
                            strlist[i],
                            System.Globalization.NumberStyles.HexNumber,
                            CultureInfo.InvariantCulture,
                            out int unicodeValue
                        )
                    )
                    {
                        decodedString.Append((char)unicodeValue);
                    }
                }

                return decodedString.ToString();
            }

            return null;
        }

        public object ConvertBack(
            object value,
            Type targetType,
            object parameter,
            CultureInfo culture
        )
        {
            if (value is string stringValue && !string.IsNullOrEmpty(stringValue))
            {
                StringBuilder htmlEncodedString = new StringBuilder();
                foreach (char c in stringValue)
                {
                    htmlEncodedString.Append($"&#x{(int)c:X};");
                }
                return htmlEncodedString.ToString();
            }
            return null;
        }
    }
}
